import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.SQLOutput;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;


public class Configuration {
    private Properties props = new Properties();

    /**
     * 读取属性配置文件
     *
     * @param confFile
     */
    public void fromFile(File confFile) {
        try (FileInputStream in = new FileInputStream(confFile);) {
            props.load(new InputStreamReader(in, StandardCharsets.UTF_8));
        } catch (IOException e) {
            throw new ValueParseException("配置文件解析错误");
        }
    }

    /**
     * 获取键值
     *
     * @param key
     * @return value
     */
    public String getProp(String key) {
        return props.getProperty(key);
    }

    /**
     * 获取布尔类型键值
     *
     * @param key
     * @return value
     */
    public boolean getBoolean(String key) {
        String value = props.getProperty(key);
        if ("true".equalsIgnoreCase(value)) {
            return true;
        }
        if ("false".equalsIgnoreCase(value)) {
            return false;
        }
        throw new ValueParseException("键值不存在");
    }

    /**
     * 获取指定键值布尔值
     *
     * @param key
     * @return Boolean
     */
    public Boolean getBooleanWithDefault(String key, Boolean defaultValue) {
        String value = props.getProperty(key);
        if (!"".equalsIgnoreCase(value)) {
            return getBoolean(key);
        } else
            return defaultValue;
    }

    /**
     * 获取指定键值整数值
     *
     * @param key
     * @return Integer
     */
    public Integer getInt(String key, int defaultValue) {
        String value = props.getProperty(key);

        if (!"".equalsIgnoreCase(value)) {
            return Integer.valueOf(value);
        } else
            return defaultValue;
    }

    /**
     * 获取指定键值日期值
     *
     * @param key
     * @return Date
     */
    public Date getDate(String key, Date defaultValue) throws ParseException {
        DateFormat format = new SimpleDateFormat("yyyyMMdd");
        String value = props.getProperty(key);
        if (!"".equalsIgnoreCase(value)) {
            Date parse = format.parse(value);
            return parse;
        } else
            return defaultValue;
    }
}